package com.jfree.netty.controller;


import com.jfree.netty.MyProtocolBean;
import com.jfree.netty.handler.ClientHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@org.springframework.web.bind.annotation.RestController
@RequestMapping("/rest")
public class RestController {

    @RequestMapping("/se")
    public void send(int i, int a) {

        //TODO netty  write线程安全吗，虽然业务线程会封装为task再nett线程中执行，但，如果一个write再netty线程中执行，
        // 一个在业务线程中执行是同同时开始的，那么谁先执行。还有如果两个都在业务线程中执行，同时往队列上，谁会先放进去？？？
        for (Map.Entry<String, ChannelHandlerContext> em : ClientHandler.map.entrySet()) {
            ChannelHandlerContext ctx = em.getValue();
            MyProtocolBean myProtocolBean = null;
            if (i == 0) {
                String le = a == 0 ? "{Hello,netty}" : "{Hello,netty}" + a;
                myProtocolBean = new MyProtocolBean((byte) 10, (byte) 12, le.length(), le);
            } else
                myProtocolBean = new MyProtocolBean((byte) 0xA, (byte) 0xC, "Hello,Netty".length() - i, "Hello,Netty");
            System.out.println("thread-wall-name:" + Thread.currentThread().getName());
            ctx.writeAndFlush(myProtocolBean).addListener((ChannelFutureListener) future -> {
                Thread.sleep(5000);
                System.out.println("thread-controller-name:" + Thread.currentThread().getName());

            });
            System.out.println("----controller sleep------");

        }
    }

    @RequestMapping("/se2")
    public void send2() {
        for (Map.Entry<String, ChannelHandlerContext> em : ClientHandler.map.entrySet()) {
            System.out.println("ctx remove=" + em.getValue().isRemoved() + "---channel isactive" +
                    em.getValue().channel().isActive() + "---channel isopen----" + em.getValue().channel().isOpen());
            em.getValue().channel().close();
        }
    }
}
